package com.christina.engine.parameter.builder;

import com.alibaba.fastjson.JSONObject;
import com.christina.service.domain.chat.model.ChatRequest;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 聊天请求建造者
 * 使用建造者模式构建ChatRequest对象
 * 
 * @author Christina
 */
@Component
public class ChatRequestBuilder extends ParameterBuilder<ChatRequest> {
    
    private static final List<String> VALID_MESSAGE_TYPES = Arrays.asList(
            "TEXT", "VOICE", "IMAGE", "FILE");
    
    private static final List<String> VALID_CHAT_MODES = Arrays.asList(
            "CASUAL", "PROFESSIONAL", "EDUCATIONAL", "ENTERTAINMENT");
    
    /**
     * 创建新的建造者实例
     * 
     * @return 建造者实例
     */
    public static ChatRequestBuilder newBuilder() {
        return new ChatRequestBuilder();
    }
    
    /**
     * 设置用户ID
     * 
     * @param userId 用户ID
     * @return 当前建造者实例
     */
    public ChatRequestBuilder userId(Long userId) {
        return (ChatRequestBuilder) addParameter("userId", userId);
    }
    
    /**
     * 设置会话ID
     * 
     * @param sessionId 会话ID
     * @return 当前建造者实例
     */
    public ChatRequestBuilder sessionId(String sessionId) {
        return (ChatRequestBuilder) addParameter("sessionId", sessionId);
    }
    
    /**
     * 设置消息内容
     * 
     * @param message 消息内容
     * @return 当前建造者实例
     */
    public ChatRequestBuilder message(String message) {
        return (ChatRequestBuilder) addParameter("message", message);
    }
    
    /**
     * 设置消息类型
     * 
     * @param messageType 消息类型
     * @return 当前建造者实例
     */
    public ChatRequestBuilder messageType(String messageType) {
        return (ChatRequestBuilder) addParameter("messageType", messageType);
    }
    
    /**
     * 设置聊天模式
     * 
     * @param chatMode 聊天模式
     * @return 当前建造者实例
     */
    public ChatRequestBuilder chatMode(String chatMode) {
        return (ChatRequestBuilder) addParameter("chatMode", chatMode);
    }
    
    /**
     * 设置聊天类型
     * 
     * @param chatType 聊天类型
     * @return 当前建造者实例
     */
    public ChatRequestBuilder chatType(String chatType) {
        return chatMode(chatType);
    }
    
    /**
     * 设置请求时间
     * 
     * @param requestTime 请求时间
     * @return 当前建造者实例
     */
    public ChatRequestBuilder requestTime(LocalDateTime requestTime) {
        return (ChatRequestBuilder) addParameter("requestTime", requestTime);
    }
    
    /**
     * 设置上下文信息
     * 
     * @param context 上下文信息
     * @return 当前建造者实例
     */
    public ChatRequestBuilder context(JSONObject context) {
        return (ChatRequestBuilder) addParameter("context", context);
    }
    
    /**
     * 添加上下文键值对
     * 
     * @param key 键
     * @param value 值
     * @return 当前建造者实例
     */
    public ChatRequestBuilder addContextItem(String key, Object value) throws ParameterValidationException {
        JSONObject context = getParameter("context", JSONObject.class);
        if (context == null) {
            context = new JSONObject();
            addParameter("context", context);
        }
        context.put(key, value);
        return this;
    }
    
    /**
     * 设置是否需要上下文感知
     * 
     * @param contextAware 是否需要上下文感知
     * @return 当前建造者实例
     */
    public ChatRequestBuilder contextAware(Boolean contextAware) {
        return (ChatRequestBuilder) addParameter("contextAware", contextAware);
    }
    
    /**
     * 设置最大响应长度
     * 
     * @param maxResponseLength 最大响应长度
     * @return 当前建造者实例
     */
    public ChatRequestBuilder maxResponseLength(Integer maxResponseLength) {
        return (ChatRequestBuilder) addParameter("maxResponseLength", maxResponseLength);
    }
    
    /**
     * 设置语言偏好
     * 
     * @param language 语言偏好
     * @return 当前建造者实例
     */
    public ChatRequestBuilder language(String language) {
        return (ChatRequestBuilder) addParameter("language", language);
    }
    
    /**
     * 设置是否需要情感分析
     * 
     * @param enableSentimentAnalysis 是否需要情感分析
     * @return 当前建造者实例
     */
    public ChatRequestBuilder enableSentimentAnalysis(Boolean enableSentimentAnalysis) {
        return (ChatRequestBuilder) addParameter("enableSentimentAnalysis", enableSentimentAnalysis);
    }
    
    /**
     * 配置默认值和验证规则
     * 
     * @return 当前建造者实例
     */
    public ChatRequestBuilder withDefaults() {
        // 设置默认值
        setDefault("messageType", "TEXT");
        setDefault("chatMode", "CASUAL");
        setDefault("requestTime", LocalDateTime.now());
        setDefault("context", new JSONObject());
        setDefault("contextAware", true);
        setDefault("maxResponseLength", 1000);
        setDefault("language", "zh-CN");
        setDefault("enableSentimentAnalysis", false);
        
        // 添加验证规则
        required("userId")
                .addValidation("userId", 
                        value -> value instanceof Long && ((Long) value) > 0,
                        "用户ID必须是正整数");
        
        required("sessionId")
                .addValidation("sessionId",
                        value -> value.toString().trim().length() >= 8,
                        "会话ID至少需要8个字符");
        
        required("message")
                .addValidation("message",
                        value -> value.toString().trim().length() > 0 && 
                                value.toString().trim().length() <= 10000,
                        "消息内容不能为空且不能超过10000字符");
        
        addValidation("messageType",
                value -> VALID_MESSAGE_TYPES.contains(value.toString().toUpperCase()),
                "消息类型必须是: " + String.join(", ", VALID_MESSAGE_TYPES));
        
        addValidation("chatMode",
                value -> VALID_CHAT_MODES.contains(value.toString().toUpperCase()),
                "聊天模式必须是: " + String.join(", ", VALID_CHAT_MODES));
        
        addValidation("maxResponseLength",
                value -> value instanceof Integer && ((Integer) value) > 0 && ((Integer) value) <= 5000,
                "最大响应长度必须在1-5000之间");
        
        addValidation("language",
                value -> value.toString().matches("^[a-z]{2}(-[A-Z]{2})?$"),
                "语言格式必须是ISO标准格式，如: zh-CN, en-US");
        
        // 添加类型转换器
        addConverter("messageType", value -> value.toString().toUpperCase());
        addConverter("chatMode", value -> value.toString().toUpperCase());
        addConverter("language", value -> value.toString().toLowerCase());
        
        return this;
    }
    
    @Override
    protected void performCustomValidation() throws ParameterValidationException {
        // 验证消息内容不包含恶意内容
        String message = getParameter("message", String.class);
        if (message != null && containsMaliciousContent(message)) {
            throw new ParameterValidationException("消息内容包含不当信息");
        }
        
        // 验证上下文大小
        JSONObject context = getParameter("context", JSONObject.class);
        if (context != null && context.toJSONString().length() > 50000) {
            throw new ParameterValidationException("上下文信息过大，不能超过50KB");
        }
        
        // 验证请求时间不能是未来时间（超过1小时）
        LocalDateTime requestTime = getParameter("requestTime", LocalDateTime.class);
        if (requestTime != null && requestTime.isAfter(LocalDateTime.now().plusHours(1))) {
            throw new ParameterValidationException("请求时间不能是未来时间");
        }
    }
    
    @Override
    protected ChatRequest doBuild() throws ParameterValidationException {
        ChatRequest.ChatRequestBuilder builder = ChatRequest.builder()
                .userId(getParameter("userId", Long.class))
                .sessionId(getParameter("sessionId", String.class))
                .message(getParameter("message", String.class))
                .requestTime(getParameter("requestTime", LocalDateTime.class));
        
        // 设置消息类型
        String messageTypeStr = getParameter("messageType", String.class);
        if (messageTypeStr != null) {
            try {
                ChatRequest.MessageType messageType = ChatRequest.MessageType.valueOf(messageTypeStr);
                builder.messageType(messageType);
            } catch (IllegalArgumentException e) {
                // 如果枚举值不存在，使用默认值
                builder.messageType(ChatRequest.MessageType.TEXT);
            }
        }
        
        // 设置上下文
        JSONObject context = getParameter("context", JSONObject.class);
        if (context != null && !context.isEmpty()) {
            builder.context(context);
        }
        
        return builder.build();
    }
    
    /**
     * 检查消息是否包含恶意内容
     * 
     * @param message 消息内容
     * @return 是否包含恶意内容
     */
    private boolean containsMaliciousContent(String message) {
        if (message == null || message.trim().isEmpty()) {
            return false;
        }
        
        String lowerMessage = message.toLowerCase();
        
        // 简单的恶意内容检测
        String[] maliciousPatterns = {
                "script>", "<script", "javascript:", "eval(",
                "drop table", "delete from", "insert into",
                "union select", "xss", "csrf"
        };
        
        for (String pattern : maliciousPatterns) {
            if (lowerMessage.contains(pattern)) {
                return true;
            }
        }
        
        return false;
    }
}